#ifndef _SERVER_H_
#include "server.h"
#endif

#include <iostream>
#include <cassert>
#include <string>

//////////////////////////////////////////////////////////////////////////


Server::Server()
{
    AddEventToObserve(Observer::NETWORK_ACCEPTED_NEW_CONNECTION);
    AddEventToObserve(Observer::NETWORK_SEND_COMPLETE);
    AddEventToObserve(Observer::NETWORK_RECEIVE_COMPLETE);

    m_Conn.AddObserver(this);
}


//////////////////////////////////////////////////////////////////////////


void Server::Accept()
{
    m_Conn.Accept();
}


//////////////////////////////////////////////////////////////////////////


void Server::SendResponse()
{
    std::string str("I have received your message");
    Buffer buffer( str.c_str(), str.length() );
    m_Conn.SendTCP(buffer);
}


//////////////////////////////////////////////////////////////////////////


void Server::OnEvent( Event _event, Observable* _observable )
{
    switch (_event)
    {
    case Observer::NETWORK_ACCEPTED_NEW_CONNECTION:
        {
            std::cout << "Server accepted new connection" << std::endl;
            break;
        }
        
    case Observer::NETWORK_SEND_COMPLETE:
        {
            std::cout << "Server sent response to client" << std::endl;
            break;
        }
        
    case Observer::NETWORK_RECEIVE_COMPLETE:
        {
            Buffer buffer = m_Conn.GetRecvPacketTCP();
            std::string str( buffer.Data(), buffer.Size() );
            std::cout << "Server received message from client: " << str << std::endl;

            SendResponse();

            break;
        }
    default:
        assert(0);
        break;
    }
}


//////////////////////////////////////////////////////////////////////////
